#include "bsp_MAX44009.h"
#include <string.h>
#include <math.h>
#include "sw_i2c.h"
#include "debug.h"

// 配置参数
void MAX44009_Configuration(void)
{
    uint8_t buff[1] = {0x80};
    Sw_I2c_Write_8addr(SW_I2C1, MAX44009_ADDR, 0x02, buff, 1);
}

uint8_t MAX44009_I2c_Read_8addr(uint8_t sel, uint8_t IICID, uint8_t regaddr, uint8_t *pdata, uint8_t rcnt) // 获取协议查看规格书17页
{
    uint8_t returnack = SW_I2C_TRUE;

    if (!rcnt)
        return SW_I2C_FALSE;

    i2c_port_initial(sel);
    i2c_start_condition(sel);
    i2c_slave_address(sel, IICID, WRITE_CMD);
    if (!i2c_check_ack(sel))
    {
        returnack = SW_I2C_FALSE;
    }
    TIMER__Wait_us(SW_I2C_WAIT_TIME);
    i2c_register_address(sel, regaddr); // 0x03
    if (!i2c_check_ack(sel))
    {
        returnack = SW_I2C_FALSE;
    }
    TIMER__Wait_us(SW_I2C_WAIT_TIME);
    i2c_start_condition(sel);
    i2c_slave_address(sel, IICID, READ_CMD);
    if (!i2c_check_ack(sel))
    {
        returnack = SW_I2C_FALSE;
    }

    TIMER__Wait_us(SW_I2C_WAIT_TIME);
    pdata[0] = Sw_I2c_Read_Data(sel);
    i2c_check_not_ack(sel);
    // 连续读取两个寄存器，在读取期间没有发送STOP条件
    i2c_port_initial(sel);
    i2c_start_condition(sel);
    i2c_slave_address(sel, IICID, WRITE_CMD);
    if (!i2c_check_ack(sel))
    {
        returnack = SW_I2C_FALSE;
    }
    TIMER__Wait_us(SW_I2C_WAIT_TIME);
    i2c_register_address(sel, regaddr + 1); // 0x04
    if (!i2c_check_ack(sel))
    {
        returnack = SW_I2C_FALSE;
    }
    TIMER__Wait_us(SW_I2C_WAIT_TIME);
    i2c_start_condition(sel);
    i2c_slave_address(sel, IICID, READ_CMD);
    if (!i2c_check_ack(sel))
    {
        returnack = SW_I2C_FALSE;
    }

    TIMER__Wait_us(SW_I2C_WAIT_TIME);
    pdata[1] = Sw_I2c_Read_Data(sel);
    i2c_check_not_ack(sel);
    i2c_stop_condition(sel);

    return returnack;
}

#if 0
uint16_t pow(uint8_t x, uint8_t y)
{
    uint16_t result = 1;
    while (y--)
    {
        result *= x;
    }
    return result;
}
#endif

static void MAX44009_Read(uint32_t *max44009_data)
{
    uint8_t buff[2] = {0}; // 获取数据
    MAX44009_I2c_Read_8addr(SW_I2C1, MAX44009_ADDR, 0x03, buff, sizeof(buff));
    printf("max44009_buff[0] :%02X,max44009_buff[1] :%02X\r\n", buff[0], buff[1]);

    if(buff[0] == 0xFF && buff[1] == 0xFF)
    {
        // *max44009_data = collec_data.max44009_data;
        printf("warning!!!\r\n");
        return;
    }
    *max44009_data = pow(2,(buff[0] >> 4)) * (((uint8_t)(buff[0] << 4) | (buff[1] & 0x0F)) * 0.045);
    printf("max44009_data:%ld\r\n",*max44009_data);
    // printf("max44009_data :%d\r\n",*max44009_data);
    /*
    光照强度 = 2^(指数)x 尾数 x0.045
    指数=8xE3+4xE2 +2xE1 + EO
    尾数=128xM7 +64xM6 + 32xM5 + 16xM4 + 8xM3 + 4xM2 +2xM1 +MO
    */
}

// 数据采集函数
void Period_MAX44009_Data_Collection(uint32_t *max44009_data)
{
    // MAX44009_Configuration(); // 配置参数
    HAL_Delay(10);
    MAX44009_Read(max44009_data);
}